package com.lingyuan.oms.handler;

import com.lingyuan.oms.constant.HandlerType;
import com.lingyuan.oms.domain.param.CreateOrderParam;
import com.lingyuan.oms.factory.HandlerFactory;

/**
 * @ClassName：ChainOfResponsibility
 * @Author: LeiHao
 * @Date: 2024/10/8 10:23
 * @Description: 责任链类可以接受枚举数组来构建责任链
 */
public class ChainOfResponsibility {
    private Handler head;

    public ChainOfResponsibility(HandlerFactory factory, HandlerType... handlerTypes) {
        for (int i = 0; i < handlerTypes.length; i++) {
            Handler handler = factory.getHandler(handlerTypes[i]);
            if (i == 0) {
                head = handler;
            } else {
                setNextForPreviousHandler(head, handler);
            }
        }
    }

    private void setNextForPreviousHandler(Handler current, Handler next) {
        if (current != null && current instanceof AbstractHandler) {
            ((AbstractHandler) current).setNext(next);
        }
    }

    public boolean process(CreateOrderParam param) {
        return head.handle(param);
    }
}
